import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import DataGrid, { Column } from "devextreme-react/data-grid";
import { CpasIcon, DevPopup } from "~/public/cpas-ui";
import { Popup, ToolbarItem } from "devextreme-react/popup";
import notify from "devextreme/ui/notify";
import { deleteteMplate, queryFileIfExistInDisk, queryTemplateNameIfExist, templateExport, templateImport, templateImportTB, templateListApi, templateRename, } from "./service";
import "./_style.less";
// import { history } from 'umi';
import { rTime } from "../../../tools/Tools";
import LogicPopup from "./components/LogicPopupDefault";
// import CloudTemplatePopup from "~/cpas-business/components-bs/components/TemplatePopup/CloudTemplatePopup";
import CloudTemplatePopup from "../../../components-bs/components/TemplatePopup/CloudTemplatePopup";
const CpasPopup = Popup;
const ReportingTemplate = (param) => {
    const renameRef = useRef();
    const BatchRollingRef = useRef();
    const deleteDataRef = useRef();
    const exportName = useRef(null);
    let PageName = param.reportType ? param.reportType : "报告系统模板";
    // const [exportName,setExportName] = useState<string>('');
    const [dataGridData, setDataGridData] = useState([]);
    // const [currentRows, setCurrentRow] = useState();
    // const [isLoading, setIsLoading] = useState<boolean>(false);
    const [isConfirm, setConfirm] = useState(false);
    const CloudPopupRef = useRef();
    let tempReportType = "报告模板";
    if (param.reportType) {
        if (param.reportType === "报告系统模板") {
            tempReportType = "报告模板";
        }
        else {
            tempReportType = param.reportType;
        }
    }
    const getTempleteList = async () => {
        try {
            const res = await templateListApi();
            const templist = res.data.filter((a) => a.tempType === (param.reportType ? param.reportType : "报告系统模板"));
            setDataGridData(templist);
        }
        catch (error) {
            console.log(error);
        }
    };
    useEffect(() => {
        getTempleteList();
    }, []);
    function getFileName(filePath) {
        // 获取最后一个反斜杠之后的字符串
        const filenameWithExt = filePath.substring(filePath.lastIndexOf("\\") + 1);
        // 获取文件名（不带扩展名），并返回
        return filenameWithExt.substring(0, filenameWithExt.lastIndexOf("."));
    }
    const exportFb = async (checkFolderPath) => {
        await templateImportTB({
            configValue: exportName.current,
            filePath: "",
            templateName: exportName.current.tempName,
            TemplateType: exportName.current.tempType,
        });
        const rs = await templateExport({
            templateName: exportName.current.tempName,
            targetPath: checkFolderPath,
            TemplateFalg: exportName.current.tempFalg,
            TemplateType: exportName.current.tempType,
        });
        if (rs.success) {
            notify("导出成功", "success", 2000);
            getTempleteList();
        }
        else {
            notify("导出失败", "error", 2000);
        }
    };
    /**
     * 点击事件 导出
     */
    const onClickTemplateExport = async () => {
        if (exportName.current === null) {
            notify("请选择您要导出的模板", "warning", 2000);
        }
        else {
            let electronComponents;
            if (window.parent) {
                //@ts-ignore
                electronComponents = window.parent.electronComponents;
            }
            else {
                //@ts-ignore
                electronComponents = window.electronComponents;
            }
            const dialog_result = await electronComponents.openDirectoryDialog();
            const checkFolderPath = dialog_result.filePaths[0];
            if (checkFolderPath !== undefined) {
                const r = await queryFileIfExistInDisk({
                    templateName: exportName.current.tempName,
                    targetPath: checkFolderPath,
                });
                if (r.data) {
                    BatchRollingRef.current.show({
                        title: "提示",
                        okCallback: async () => {
                            await exportFb(checkFolderPath);
                        },
                    });
                }
                else {
                    await exportFb(checkFolderPath);
                    // const rs = await templateExport({
                    //   templateName: exportName.current.tempName,
                    //   targetPath: checkFolderPath,
                    //   TemplateFalg: exportName.current.tempFalg,
                    //   TemplateType: exportName.current.tempType,
                    // });
                    // if (rs.success) {
                    //   notify("导出成功", "success", 2000);
                    //   getTempleteList();
                    // } else {
                    //   notify("导出失败", "error", 2000);
                    // }
                }
            }
        }
    };
    /**
     * 点击事件 导入
     */
    const onClickTemplateImport = async (param) => {
        let electronComponents;
        if (window.parent) {
            //@ts-ignore
            electronComponents = window.parent.electronComponents;
        }
        else {
            //@ts-ignore
            electronComponents = window.electronComponents;
        }
        const dialog_result = await electronComponents.openFileDialog("rar");
        const checkFilePath = dialog_result.filePaths[0];
        if (checkFilePath !== undefined) {
            const newName = getFileName(checkFilePath);
            const r = await queryTemplateNameIfExist({
                templateName: newName,
                TemplateType: PageName,
            });
            if (r.data) {
                BatchRollingRef.current.show({
                    title: "提示",
                    okCallback: async () => {
                        const res = await templateImport({
                            filePath: checkFilePath,
                            TemplateType: PageName,
                            editUserName: param.UserName,
                        });
                        if (res.success) {
                            notify("导入成功", "success", 2000);
                            getTempleteList();
                        }
                        else {
                            notify(`导入失败: ${res?.msg || res.data}`, "error", 2000);
                        }
                    },
                });
            }
            else {
                const rs = await templateImport({
                    filePath: checkFilePath,
                    TemplateType: PageName,
                    editUserName: param.UserName,
                });
                if (rs.success) {
                    notify("导入成功", "success", 2000);
                    getTempleteList();
                }
                else {
                    debugger;
                    notify(`导入失败: ${rs.msg || rs.data}`, "error", 2000);
                }
            }
        }
    };
    const Grid = () => {
        return (_jsxs(DataGrid, { className: "PaperDevSortableGrid", 
            // ref={DevSortableGridRef}
            dataSource: dataGridData, keyExpr: "id", 
            // columnAutoWidth={true}
            focusedRowEnabled: true, hoverStateEnabled: true, showBorders: true, showColumnLines: true, allowColumnReordering: true, 
            // 显示行的线
            showRowLines: true, allowColumnResizing: true, columnChooser: { enabled: true }, columnFixing: { enabled: true }, headerFilter: { visible: true }, paging: { enabled: false }, cellHintEnabled: true, searchPanel: {
                visible: true,
                width: 230,
                placeholder: "",
            }, loadPanel: { enabled: true }, toolbar: {
                items: [
                    {
                        location: "before",
                        text: PageName,
                    },
                    {
                        location: "after",
                        widget: "dxButton",
                        options: {
                            type: "default",
                            icon: "iconfont icon-icon-zaixianxiangmuliebiao",
                            text: "云端下载",
                            onClick: () => {
                                // notify("该功能正在开发中......", 'warning', 2000)
                                CloudPopupRef.current.showTemplate();
                            },
                        },
                    },
                    {
                        widget: "dxButton",
                        location: "after",
                        options: {
                            icon: "iconfont icon-daoru",
                            text: "导入",
                            onClick: () => {
                                onClickTemplateImport(param);
                            },
                        },
                    },
                    {
                        widget: "dxButton",
                        location: "after",
                        options: {
                            icon: "iconfont icon-daochudigao",
                            text: "导出",
                            onClick: () => {
                                onClickTemplateExport();
                            },
                        },
                    },
                    {
                        name: "searchPanel",
                    },
                    {
                        location: "after",
                        widget: "dxButton",
                        cssClass: "refreshButton_Style",
                        options: {
                            icon: "iconfont icon-refresh",
                            onClick: async () => {
                                getTempleteList();
                            },
                        },
                    },
                ],
            }, 
            // columnResizingMode="widget"
            columnMinWidth: 100, onCellClick: (e) => {
                exportName.current = e.data;
                // setExportName(e.data.tempName)
            }, children: [_jsx(Column, { allowResizing: true, allowHeaderFiltering: false, caption: "\u62A5\u544A\u53CA\u9644\u6CE8\u6A21\u677F", dataField: "tempName", alignment: "left", minWidth: 100 }), _jsx(Column, { allowHeaderFiltering: false, allowResizing: true, alignment: "left", caption: "\u8BF4\u660E", dataField: "memo", width: 200 }), _jsx(Column, { caption: "\u62A5\u544A\u7C7B\u578B", dataField: "reportType", alignment: "left", allowHeaderFiltering: false, allowResizing: true, width: 100 }), _jsx(Column, { caption: "\u6A21\u677F\u5206\u7C7B", dataField: "tempFalg", alignment: "left", allowHeaderFiltering: false, allowResizing: true, width: 100 }), _jsx(Column, { caption: "\u5236\u4F5C\u4EBA", dataField: "editUserName", alignment: "left", allowHeaderFiltering: false, allowResizing: true, width: 50 }), _jsx(Column, { caption: "\u5236\u4F5C\u65F6\u95F4", dataField: "editDate", alignment: "right", allowHeaderFiltering: false, allowResizing: true, customizeText: (item) => {
                        return item.value ? rTime(item.value) : item.value;
                    }, width: 150 }), _jsx(Column, { caption: "\u64CD\u4F5C", alignment: "center", width: 110, cellRender: (cell) => {
                        return (_jsxs("div", { style: {
                                display: "flex",
                                alignContent: "center",
                                justifyContent: "center",
                            }, children: [_jsx("div", { className: "Icon_Style", children: _jsx(CpasIcon, { type: "icon-rename-copy", onClick: () => {
                                            renameRef.current.show({
                                                title: "设置",
                                                okCallback: async (v) => {
                                                    if (cell.data.tempName !== v) {
                                                        const r = await templateRename({
                                                            oldName: cell.data.tempName,
                                                            newName: v,
                                                            TemplateType: PageName,
                                                        });
                                                        if (r) {
                                                            exportName.current.tempName = v;
                                                            notify("修改成功", "success", 2000);
                                                            getTempleteList();
                                                        }
                                                        if (r.data.msg === "新模板名已存在,请重新命名")
                                                            notify("新模板名已存在,请重新命名", "warning", 2000);
                                                    }
                                                    else {
                                                        notify("保存成功", "success", 2000);
                                                    }
                                                },
                                                value: cell.data.tempName,
                                            });
                                        } }) }), _jsx("div", { className: "Icon_Style", children: _jsx(CpasIcon, { type: "icon-delete", onClick: () => {
                                            setConfirm(true);
                                            deleteDataRef.current = cell.data;
                                        } }) })] }));
                    } })] }));
    };
    return (_jsxs("div", { children: [useMemo(() => {
                return Grid();
            }, [dataGridData]), _jsxs(CpasPopup, { visible: isConfirm, dragEnabled: true, showCloseButton: true, showTitle: true, onHiding: () => {
                    setConfirm(false);
                }, title: "\u63D0\u793A", width: 450, height: 180, children: [_jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "取消",
                            onClick: () => {
                                setConfirm(false);
                            },
                        } }), _jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "确认",
                            type: "default",
                            onClick: async () => {
                                console.log(deleteDataRef.current, "deleteDataRef.current---");
                                if (Object.keys(deleteDataRef.current).length === 0) {
                                    notify("请选择您要删除的模板", "warning", 2000);
                                }
                                else {
                                    const name = deleteDataRef.current.tempName;
                                    const r = await deleteteMplate({
                                        templateName: name,
                                        TemplateType: PageName,
                                    });
                                    if (r) {
                                        setConfirm(false);
                                        notify("删除成功", "success", 2000);
                                        getTempleteList();
                                        exportName.current = null;
                                    }
                                }
                            },
                        } }), _jsxs("p", { children: ["\u60A8\u786E\u8BA4\u8981\u5220\u9664", " ", _jsx("span", { style: { color: "red" }, children: deleteDataRef.current
                                    ? deleteDataRef.current.tempName
                                    : "未获取到模板名称" }), "\u5417?"] })] }), _jsx(DevPopup.Input, { ref: renameRef }), _jsx(CloudTemplatePopup, { ref: CloudPopupRef, reloadTable: () => {
                    getTempleteList();
                }, cloudData: {
                    cloudTempType: tempReportType,
                    localTempTypeList: dataGridData,
                } }), _jsx(LogicPopup, { ref: BatchRollingRef })] }));
};
export default ReportingTemplate;
